#include "osal_timer.h"

void osal_timer_init(osal_timer_t* timer)
{
    timer->time = (struct timeval){0, 0};
}

void osal_timer_cutdown(osal_timer_t* timer, unsigned int timeout)
{
    struct timeval now;
    gettimeofday(&now, NULL);
    struct timeval interval = {timeout / 1000, (timeout % 1000) * 1000};
    timeradd(&now, &interval, &timer->time);
}

char osal_timer_is_expired(osal_timer_t* timer)
{
    struct timeval now, res;
    gettimeofday(&now, NULL);
    timersub(&timer->time, &now, &res);
    return ((res.tv_sec < 0) || (res.tv_sec == 0 && res.tv_usec <= 0));
}

int osal_timer_remain(osal_timer_t* timer)
{
    struct timeval now, res;
    gettimeofday(&now, NULL);
    timersub(&timer->time, &now, &res);
    return (res.tv_sec < 0) ? 0 : res.tv_sec * 1000 + res.tv_usec / 1000;
}

unsigned long osal_timer_now(void)
{
    return (unsigned long) time(NULL);
}

void osal_timer_usleep(unsigned long usec)
{
    usleep(usec);
}
